<template>
  <div class="main-wrapper">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="名称" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item">
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.statusName" :value="item.key" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row>
      <el-table-column label="用户名称" align="center">
        <template slot-scope="{row}">
          {{ row.name }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="推广标签" align="center">
        <template slot-scope="{row}">
          {{ row.adTag }}
        </template>
      </el-table-column> -->
      <el-table-column label="推荐信息" align="center">
        <template slot-scope="{row}">
          {{ row.recommend }}
        </template>
      </el-table-column>
      <el-table-column label="形象照片" width="180" align="center">
        <template slot-scope="{row}">
          <img v-if="row.avatar" style="width:160px;" :src="getFullImageUrl(row.avatar)">
        </template>
      </el-table-column>
      <el-table-column label="类型" width="80" align="center">
        <template slot-scope="{row}">
          {{ row.type | typeFilter() }}
        </template>
      </el-table-column>
      <el-table-column label="顺序" width="60" align="center">
        <template slot-scope="{row}">
          {{ row.sort }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | styleFilter()">{{ row.status | statusFilter() }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="132" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | timeFilter('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220">
        <template slot-scope="{row}">
          <el-button size="mini" type="success" @click="handleDetail(row)">详情</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">修改</el-button>
          <el-button v-if="row.status!=0" size="mini" type="danger" @click="delHightContractor(row)">删除</el-button>
          <el-button v-if="row.status!=1" size="mini" type="success" @click="reuseHightContractor(row)">恢复</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchHightContractorList" />

    <el-dialog ref="dataForm" title="选择优质承接方" top="3vh" width="68%" :visible.sync="dialogUserVisible">
      <el-table
        ref="multipleTable"
        :data="userList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="用户名称" align="center">
          <template slot-scope="{row}">
            {{ row.name }}
          </template>
        </el-table-column>
        <el-table-column label="所在省ID" align="center">
          <template slot-scope="{row}">
            {{ row.provinceName }}{{ row.cityName }}
          </template>
        </el-table-column>
        <el-table-column label="服务等级" align="center" width="80">
          <template slot-scope="{row}">
            {{ row.serviceLevel }}
          </template>
        </el-table-column>
        <el-table-column label="经营范围" align="center">
          <template slot-scope="{row}">
            {{ row.busiScope }}
          </template>
        </el-table-column>
        <el-table-column label="专业范围" align="center">
          <template slot-scope="{row}">
            {{ row.profScope }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="132">
          <template slot-scope="{row}">
            <span>{{ row.createTime | timeFilter('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="80">
          <template slot-scope="{row}">
            <el-tag :type="row.status | styleFilter()">{{ row.status | statusFilter() }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="userTotal>0" :total="userTotal" :page.sync="userQuery.page" :limit.sync="userQuery.limit" @pagination="fetchUserList" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUserVisible = false">取消</el-button>
        <el-button type="primary" @click="createHightContractor()">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改" top="3vh" :visible.sync="dialogFormVisible">
      <el-form :model="hightContractorData" label-position="left" label-width="90px">
        <el-form-item label="承接方名称">
          <span>{{ hightContractorData.name }}</span>
        </el-form-item>
        <!-- <el-form-item label="推广标签">
          <span>{{ hightContractorData.adTag }}</span>
        </el-form-item> -->
        <el-form-item label="推荐信息">
          <el-input v-model="hightContractorData.recommend" type="textarea" maxlength="160" rows="4" show-word-limit placeholder="请填写推荐信息" />
        </el-form-item>
        <el-form-item label="形象图片">
          <el-upload
            class="image-uploader"
            action="#"
            :show-file-list="false"
            :http-request="uploadImage"
          >
            <img v-if="hightContractorData.avatar" :src="getFullImageUrl(hightContractorData.avatar)" class="avatar">
            <i v-else class="el-icon-upload avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="类型">
          <span>{{ hightContractorData.type | typeFilter() }}</span>
        </el-form-item>
        <el-form-item label="显示顺序">
          <el-input v-model="hightContractorData.sort" type="number" style="width: 220px" placeholder="请填写显示顺序" />
        </el-form-item>
        <el-form-item label="状态">
          <el-tag :type="hightContractorData.status | styleFilter()">{{ hightContractorData.status | statusFilter() }}</el-tag>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ hightContractorData.createTime | timeFilter('{y}-{m}-{d} {h}:{i}') }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button type="primary" @click="updateHightContractor()">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="详情" :visible.sync="dialogDetailVisible">
      <el-form :model="hightContractorData" label-position="left" label-width="90px">
        <el-form-item label="接包方名称">
          <span>{{ hightContractorData.name }}</span>
        </el-form-item>
        <!-- <el-form-item label="推广标签">
          <span>{{ hightContractorData.adTag }}</span>
        </el-form-item> -->
        <el-form-item label="推荐信息">
          <span>{{ hightContractorData.recommend }}</span>
        </el-form-item>
        <el-form-item label="形象图片">
          <span>{{ hightContractorData.avatar }}</span>
        </el-form-item>
        <el-form-item label="类型">
          <span>{{ hightContractorData.type | typeFilter() }}</span>
        </el-form-item>
        <el-form-item label="显示顺序">
          <span>{{ hightContractorData.sort }}</span>
        </el-form-item>
        <el-form-item label="状态">
          <el-tag :type="hightContractorData.status | styleFilter()">{{ hightContractorData.status | statusFilter() }}</el-tag>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ hightContractorData.createTime | timeFilter('{y}-{m}-{d} {h}:{i}') }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDetailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList } from '@/api/user'
import { getHightContractorList, addHightContractor, editHightContractor, editHightContractorStatus } from '@/api/hightContractor'
import { getByXml, getImageUrl, parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { uploadFileData } from '@/api/upload'

export default {
  name: 'HightContractor',
  components: {
    Pagination
  },
  filters: {
    styleFilter(style) {
      const styleMap = { 1: 'success', 0: 'danger' }
      return styleMap[style]
    },
    timeFilter(time, format) {
      return parseTime(time, format)
    },
    statusFilter(value) {
      const statusMap = { 0: '无效', 1: '有效' }
      return statusMap[value]
    },
    typeFilter(value) {
      const statusMap = { 1: '个人', 2: '企业机构' }
      return statusMap[value]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      statusOptions: [
        { key: 0, statusName: '无效' },
        { key: 1, statusName: '有效' }
      ],
      hightContractorData: {},
      dialogFormVisible: false,
      dialogUserVisible: false,
      dialogDetailVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      rules: {},
      userList: [],
      userQuery: {
        page: 1,
        limit: 20
      },
      userTotal: 0,
      selectedUser: []
    }
  },
  created() {
    this.fetchHightContractorList()
  },
  methods: {
    fetchHightContractorList() {
      this.listLoading = true
      getHightContractorList(this.listQuery).then(response => {
        this.list = response.data
        // this.total = response.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchHightContractorList()
    },
    resetHightContractorData() {
      this.hightContractorData = {}
    },
    handleDetail(row) {
      this.hightContractorData = Object.assign({}, row)
      this.dialogDetailVisible = true
    },
    handleCreate() {
      this.resetHightContractorData()
      this.dialogStatus = 'create'
      this.dialogUserVisible = true
      this.fetchUserList()
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    createHightContractor() {
      console.log(this.selectedUser)
      if (this.selectedUser && this.selectedUser.length > 0) {
        this.selectedUser.forEach(item => {
          addHightContractor(item).then(res => {
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          })
        })
        this.dialogUserVisible = false
      }
    },
    handleUpdate(row) {
      this.hightContractorData = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    updateHightContractor() {
      const tempData = Object.assign({}, this.hightContractorData)
      editHightContractor(tempData).then(() => {
        for (const v of this.list) {
          if (v.id === this.hightContractorData.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, this.hightContractorData)
            break
          }
        }
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    delHightContractor(row) {
      row.status = 0
      this.updateHightContractorStatus(row, 0).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      })
    },
    reuseHightContractor(row) {
      row.status = 1
      this.updateHightContractorStatus(row, 1).then(() => {
        this.$notify({
          title: '成功',
          message: '数据恢复成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      })
    },
    updateHightContractorStatus(row, status) {
      row.status = status
      editHightContractorStatus(row.id, status).then(() => {
        this.hightContractorData = Object.assign({}, row)
        this.hightContractorData.status = status
        for (const v of this.list) {
          if (v.id === this.hightContractorData.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, this.hightContractorData)
            break
          }
        }
      })
      this.$message({
        message: '操作成功',
        type: 'success'
      })
    },
    fetchUserList() {
      this.listLoading = true
      getUserList({ status: 1 }).then(response => {
        console.log(response)
        this.userList = response.data.items
        this.userTotal = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleSelectionChange(val) {
      console.log('handleSelectionChange====', val)
      this.selectedUser = val
    },
    uploadImage(e) {
      uploadFileData(e.file).then(res => {
        console.log(res)
        this.hightContractorData.avatar = getByXml(res, 'Key')
        console.log(this.hightContractorData)
      })
    },
    getFullImageUrl(imgName) {
      return getImageUrl(imgName)
    }
  }
}
</script>
<style lang="scss" scoped>
.main-wrapper {
  margin: 8px;
  .filter-container {
    padding: 10px 0;
    .filter-item {
      width: 200px;
      margin-right: 10px;
    }
  }
  .image-uploader {
    border: 1px dashed #d9d9d9;
    width: 278px;
    height: 178px;
    .el-upload {
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 278px;
      height: 178px;
      display: block;
    }
  }
}
</style>
